import axios from "axios";
import i18n from "@/locale";
import { clearLoginInfo } from "./storage";
import { refresh } from "@/api/auth";
import { Modal, notification } from "ant-design-vue";
import { ACCESS_TOKEN, REFRESH_TOKEN } from "./storage/key";
import type { AxiosError } from "axios";
import router from "@/router";
type RequestError = AxiosError<{
  message?: string;
  result?: any;
  errorMessage?: string;
}>;
const request = axios.create({
  baseURL: process.env.NODE_ENV === "development" ? "/api" : "",
  timeout: 10 * 1000, // 过期时间
});

let isRefreshing = false;
const queue: ((refreshError?: boolean) => any)[] = [];

export const CONTENT_TYPE_MULTIPART_FORM_DATA = {
  "Content-Type": "multipart/form-data",
};

// 重定向到登录页
const gotoLoginPage = () => {
  location.replace(
    "/white-path/login?path=" + encodeURIComponent(location.pathname)
  );
};
// 请求错误处理
const errorHandler = (error: RequestError) => {
  if (error.response) {
    const { data = {}, status } = error.response;
    Modal.error({
      title: i18n.global.t("请求错误"),
      content: data?.message,
    });
    // 403 无权限
    if (status === 403) {
      notification.error({
        message: i18n.global.t("无此权限"),
        description: i18n.global.t("您无权访问此资源"),
      });
    }
    // 401 未登录/未授权
    if (status === 401 && data.result) {
      notification.error({
        message: i18n.global.t("无此权限"),
        description: i18n.global.t("访问此资源需完全身份认证"),
      });
    }
  }
  return error.response?.data;
};

// 请求拦截器
request.interceptors.request.use((config) => {
  if (config.url === "/auth/refresh") {
    config.headers.Authorization = localStorage.getItem(REFRESH_TOKEN);
  } else {
    config.headers.Authorization = localStorage.getItem(ACCESS_TOKEN);
  }
  config.params = {
    ...config.params,
    lang: "zh-CN",
    fc: router.currentRoute.value.name,
  };
  return config;
});

// 响应拦截器
request.interceptors.response.use((response) => {
  const { config, data } = response;
  if (data?.code === 401) {
    // 非刷新接口
    if (config.url != "/auth/refresh") {
      // 没在刷新
      if (!isRefreshing) {
        isRefreshing = true;
        refresh().then(({ success, result }) => {
          isRefreshing = false;
          if (success) {
            localStorage.setItem(ACCESS_TOKEN, result.accessToken);
            localStorage.setItem(REFRESH_TOKEN, result.refreshToken);
            queue.forEach((fn) => fn());
          } else {
            notification.error({
              message: i18n.global.t("访问失败"),
              description: data?.message,
            });
            // 刷新失败清空队列
            queue.forEach((fn) => fn(true));
            // 清空storage
            clearLoginInfo();
            gotoLoginPage();
          }
        });
      }
      // 添加Promise到队列
      return new Promise((resolve) => {
        queue.push((refreshError = false) =>
          resolve(refreshError ? data : request(config))
        );
      });
    }
  } else if (!(data instanceof Blob) && data?.code !== 200) {
    let content = data?.message;
    if (data.code == 403) {
      content += `: ${data?.result}`;
    }
    Modal.error({ title: i18n.global.t("请求错误"), content });
  }
  return data;
}, errorHandler);

export { request };
